import { positions } from "./position";
import type { Position } from "./position";

// 图片点击定位事件
export const imgTouchPosition = (
  type: number,
  x: number,
  y: number
): Position | null => {
  const data = positions[type - 1];
  for (let i = 0; i < data.length; i++) {
    const posx = data[i].x;
    const posy = data[i].y;
    for (let j = 0; j < posx.length; j++) {
      if (
        posx[j][0] <= x &&
        posx[j][1] >= x &&
        posy[j][0] <= y &&
        posy[j][1] >= y
      ) {
        return data[i];
      }
    }
  }
  return null;
};

// 本地存储完成状态
export const storageState = (index: number) => {
  const state = sessionStorage.getItem("complete");
  let res = null;
  if (state) {
    res = JSON.parse(state);
    res[index] = 1;
  } else {
    res = [0, 0, 0, 0, 0];
  }
  sessionStorage.setItem("complete", JSON.stringify(res));
};

// 微信分享
const appId = "wx941907cf45112afa";
const nonceStr = "Wm3WZYTPz0wzccnW";
const timestamp = parseInt((new Date().getTime() / 1000).toString()) + "";
export const wechatShare = () => {
  const signature = getCrypto();
  window.wx.config({
    debug: true,
    appId: appId,
    timestamp: timestamp,
    nonceStr: nonceStr,
    signature: signature,
    jsApiList: ["onMenuShareAppMessage", "updateTimelineShareData"],
  });

  window.wx.ready(function () {
    console.log("ready");
    window.wx.onMenuShareAppMessage({
      title: "分享标题",
      desc: "分享描述",
      link: "https://example.com",
      imgUrl: "https://example.com/image.jpg",
      success: function () {
        console.log("分享成功");
      },
      cancel: function () {
        console.log("分享取消");
      },
    });

    window.wx.updateTimelineShareData({
      title: "分享标题",
      link: "https://example.com",
      imgUrl: "https://example.com/image.jpg",
      success: function () {
        console.log("分享成功");
      },
      cancel: function () {
        console.log("分享取消");
      },
    });

    window.wx.onMenuShareTimeline({
      title: "分享标题",
      link: "https://example.com",
      imgUrl: "https://example.com/image.jpg",
      success: function () {
        // 用户点击了分享后执行的回调函数
        console.log("分享成功2");
      },
      cancel: function () {
        console.log("分享取消2");
      },
    });
  });

  window.wx.error(function (res) {
    console.error("微信JS-SDK配置失败", res);
  });
};
const getCrypto = async () => {
  const ticket = localStorage.getItem("ticket") || "";
  const url = window.location.href.split("#")[0];
  const string = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${encodeURIComponent(
    url
  )}`;
  const encoder = new TextEncoder();
  const data = encoder.encode(string);
  const hashBuffer = await crypto.subtle.digest("SHA-1", data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray
    .map((byte) => byte.toString(16).padStart(2, "0"))
    .join("");

  return hashHex;
};
